import { create } from 'zustand'
import { ArticleSteps, Move } from './art-add-store'
import { devtools, persist } from 'zustand/middleware'
import { immer } from 'zustand/middleware/immer'
import { getStorage } from '@/utils/storage.ts'
import { getArticleApi } from '@/api/article-api'
import to from 'await-to-js'
import config from '@/config.json'

type EditStoreType = {
  // 当前所处的步骤
  current: ArticleSteps
  // 正在被编辑的文章的数据
  article: ArticleEditForm
}

// 初始数据
const initialState: EditStoreType = {
  current: ArticleSteps.base,
  article: {} as ArticleEditForm
}

// 创建 Store 的 hook
const useArtEditStore = create<EditStoreType>()(
  immer(
    devtools(
      persist(
        () => {
          return {
            ...initialState
          }
        },
        {
          name: 'art-edit-store',
          storage: getStorage(),
          partialize(state) {
            return { article: state.article }
          }
        }
      ),
      { name: 'art-edit-store' }
    )
  )
)

// 向外导出 Store 的 hook
export default useArtEditStore

// actions
export const initArticle = async (id: string) => {
  const [err, res] = await to(getArticleApi(id))
  if (err) return null
  useArtEditStore.setState((state) => {
    if (res.data) {
      state.article = res.data
    }
  })
  return true
}
export const updateBase = (values: Partial<ArticleBaseForm>) => {
  useArtEditStore.setState((state) => {
    state.article = { ...state.article, ...values }
  })
}
export const updateCurrent = (move: Move = Move.next) => {
  useArtEditStore.setState((state) => {
    state.current += move
  })
}
export const resetCurrent = () => {
  useArtEditStore.setState((state) => {
    state.current = ArticleSteps.base
  })
}
export const setArticleCover = (cover: Blob) => {
  useArtEditStore.setState((state) => {
    state.article.cover_img = cover
  })
}
// 存储文章内容
export const setContent = (content: string) => {
  useArtEditStore.setState((state) => {
    state.article.content = content
  })
}
// 更新文章的发布状态
export const setState = (artState: '草稿' | '已发布') => {
  useArtEditStore.setState((state) => {
    state.article.state = artState
  })
}

// selectors
export const selectCurrent = (state: EditStoreType) => state.current
export const selectBase = (state: EditStoreType) => ({ title: state.article.title, cate_id: state.article.cate_id })
export const selectCover = (state: EditStoreType) => {
  const cover = state.article.cover_img
  return !cover ? null : typeof cover === 'string' ? config.baseURL + cover : URL.createObjectURL(cover)
}
export const selectContent = (state: EditStoreType) => state.article.content
export const selectIsShowDraft = (state: EditStoreType) => state.article.state === '草稿'
